<template>
  <div class="search">
    <div class="searchInfo">
    </div>
    <a-button type="primary" @click="toAdd">
      灰度部署
    </a-button>
  </div>
  <a-table
    :dataSource="tableData.data"
    :columns="tableData.listColumns"
    :pagination="false"
    bordered
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex === 'operation'">
        <a @click="toSetScale(record)"> 设置副本数</a>
        <a-popconfirm
          title="是否确定发布？"
          cancel-text="否"
          ok-text="是"
          @confirm="deploy(record)"
        >
          <a v-if="record.runningType === 'g'" style="padding-left: 10px">发布</a>
        </a-popconfirm>
        <a-popconfirm
          title="是否确定销毁？"
          cancel-text="否"
          ok-text="是"
          @confirm="destroy(record)"
        >
          <a v-if="record.runningType === 'g'" style="padding-left: 10px">销毁</a>
        </a-popconfirm>
      </template>
    </template>
  </a-table>

  <a-modal
    v-model:visible="addForm.visible"
    title="发布"
    okText="确定"
    cancelText="取消"
    width="30%"
    :maskClosable="false"
    centered
    @ok="add"
    @cancel="cancelAdd"
  >
    <a-form
      :model="addForm.data"
      name="addForm"
      ref="addFormRef"
      v-bind="formLayout"
    >
      <a-form-item
        label="制品镜像"
        name="moduleBuildId"
        :rules="[{ required: true, message: '请选择制品构建' }]"
      >
        <a-select
            v-model:value="addForm.data.moduleBuildId"
            :options="state.moduleBuildIdData"
            :filter-option="false"
            :fieldNames="state.moduleBuildIdFieldNames"
        ></a-select>
      </a-form-item>
      <a-form-item
        label="header-key"
        name="headerKey"
        :rules="[{ message: '只能输入(字母,数字,-),最大长度为20', pattern: /^[a-zA-Z0-9-]{1,20}$/ }]"
      >
        <a-input v-model:value="addForm.data.headerKey" />
      </a-form-item>
      <a-form-item
        label="header-value"
        name="headerValue"
        :rules="[{ message: '只能输入(字母,数字,-),最大长度为20', pattern: /^[a-zA-Z0-9-]{1,20}$/ }]"
      >
        <a-input v-model:value="addForm.data.headerValue" />
      </a-form-item>
    </a-form>
  </a-modal>
  <a-modal v-model:visible="scaleForm.visible" title="设置副本数" @ok="setScale" width="280px">
    <a-input-number id="inputNumber" v-model:value="scaleForm.scale" :min="0" :max="10" />
  </a-modal>
</template>

<script lang="ts">
import { defineComponent, toRefs } from "vue";
import { reactive, ref } from "@vue/reactivity";
import {
  PlusOutlined,
  ReloadOutlined,
  SearchOutlined,
} from "@ant-design/icons-vue";
import { moduleRunningApi, moduleBuildApi } from "@/api/devcloudApi";
import { message } from "ant-design-vue";
import { clearObject, clone, deleteKeyIgnore } from "@/util/utils";

export default defineComponent({
  name: "moduleRunning",
  components: {
    ReloadOutlined,
    SearchOutlined,
    PlusOutlined,
  },
  props: {
    moduleId: {
      type: Number,
      required: false,
    },
  },
  setup(props) {
    const { moduleId } = toRefs(props);
    const returnObj: any = {};

    const formLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
    };

    // ------------ 查询条件 ------------------------
    const query: any = reactive({
      moduleId: "",
      moduleBuildId: "",
      headerKey: "",
      headerValue: "",
      scale: "",
    });

    const search = () => {
      list();
    };

    const initQuery = () => {
      query.moduleId = moduleId.value;
    };

    const reload = () => {
      initQuery();
      list();
    };

    returnObj.query = query;
    returnObj.search = search;
    returnObj.reload = reload;

    // ------------ 添加弹框 ------------------------
    const addFormRef = ref();
    const addForm: any = reactive({
      visible: false,
      data: {},
    });

    const initAddForm = () => {
      addForm.data.moduleId= moduleId.value
    };

    const toAdd = async () => {
      initAddForm();
      addForm.visible = true;
    };

    const cancelAdd = () => {
      addFormRef.value.resetFields();
      addForm.visible = false;
    };

    const add = () => {
      addFormRef.value.validateFields().then(async () => {
        const res = await moduleRunningApi.insert(addForm.data);
        if (res.success) {
          message.success("添加成功");
          reflush();
          cancelAdd();
        }
      });
    };

    returnObj.addFormRef = addFormRef;
    returnObj.addForm = addForm;
    returnObj.toAdd = toAdd;
    returnObj.cancelAdd = cancelAdd;
    returnObj.add = add;

    // ------------ 表格 ------------------------
    const tableData = reactive({
      data: [],
      listColumns: [
        {
          title: "名称",
          dataIndex: "name",
          key: "name",
          width: "100px",
          align: "center",
        },
        {
          title: "分支",
          dataIndex: "branch",
          key: "branch",
          width: "50px",
          align: "center",
        },
        {
          title: "header-key",
          dataIndex: "headerKey",
          key: "headerKey",
          width: "50px",
          align: "center",
        },
        {
          title: "header-key",
          dataIndex: "headerValue",
          key: "headerValue",
          width: "50px",
          align: "center",
        },
        {
          title: "副本数",
          dataIndex: "scale",
          key: "scale",
          width: "20px",
          align: "center",
        },
        {
          title: "类型",
          dataIndex: "runningTypeDesc",
          key: "runningTypeDesc",
          width: "20px",
          align: "center",
        },
        {
          title: "操作",
          dataIndex: "operation",
          width: "100px",
          align: "center",
        },
      ],
    });

    const list = async () => {
      clearObject(query);
      const res = await moduleRunningApi.page(query);
      if (res.success) {
        tableData.data = res.result;
      }
    };

    const reflush = () => {
      moduleBuildIdList()
      initQuery();
      list();
    };

    const deploy = async (item: any) => {
      const res = await moduleRunningApi.deploy(item.id);
      if (res.success) {
        message.success("发布成功");
        reflush();
      }
    };

    const destroy = async (item: any) => {
      const res = await moduleRunningApi.delete(item.id);
      if (res.success) {
        message.success("销毁成功");
        reflush();
      }
    };

    
    const scaleForm: any = reactive({
      visible: false,
      data: {},
    });

    const toSetScale = (item: any)=>{
      scaleForm.select = item
      scaleForm.scale = item.scale
      scaleForm.visible = true
    }
    

    const setScale = async ()=>{
      if(scaleForm.scale === scaleForm.select.scale){
        message.warn("副本没有变化")
        return
      }
      const param = {
        id: scaleForm.select.id,
        deploymentName: scaleForm.select.name,
        scale: scaleForm.scale
      }
      
      const res = await moduleRunningApi.setSacle(param);
      if (res.success) {
        list()
        scaleForm.visible = false
      }
    }

    returnObj.scaleForm = scaleForm;
    returnObj.toSetScale = toSetScale;
    returnObj.setScale = setScale;
    returnObj.reflush = reflush;
    returnObj.tableData = tableData;
    returnObj.deploy = deploy;
    returnObj.destroy = destroy;


    const state = reactive({
      moduleBuildIdData: [],
      moduleBuildIdFieldNames: {
        value: "id",
        label: "imageName",
      },
    })

    // ------------查询------------------

    const moduleBuildIdList = async () => {
      const param = {
        moduleId: moduleId.value
      }
      const res = await moduleBuildApi.listRunEnable(param)
      if (res.success) {
        res.result = res.result.filter((item: { runningFlag: number; })=>item.runningFlag ===0)
        res.result.forEach((item: { branch: string; imageName: any; })=>{
          const imageName = item.imageName
          item.imageName = item.branch + "@" + imageName.substring(imageName.lastIndexOf('/')+2)
        })
        state.moduleBuildIdData = res.result
      }
    }

    // --------------初始化--------------------------

    const initData = () => {
      reflush();
    };

    initData();

    return {
      ...returnObj,
      formLayout,
      state,
    };
  },
});
</script>

<style lang="less" scoped>
.search {
  display: flex;
  justify-content: space-between;
  padding: 40px 90px 0 50px;
}
.ant-table-wrapper {
  margin: 40px;
}

.searchInfo {
  width: 80%;
  display: flex;

  .ant-input {
    width: 180px;
    margin: 0 10px;
  }
  .ant-select {
    width: 180px;
    margin: 0 10px;
  }
  .search-btn {
    margin: 0 10px;
  }
}
.ant-pagination {
  padding-top: 20px;
}
.ant-modal {
  .ant-input {
    width: 280px;
  }
  .ant-select {
    width: 280px;
  }
  .ant-picker {
    width: 200px;
  }
  .ant-input-number {
    width: 100px;
  }
}
</style>